mergeInto(LibraryManager.library, {
  StartRecording: function() {
    try {
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ audio: true })
          .then(function(stream) {
            // 创建MediaRecorder实例
            window.mediaRecorder = new MediaRecorder(stream);
            window.audioChunks = [];
            
            // 收集音频数据
            window.mediaRecorder.ondataavailable = function(e) {
              if (e.data.size > 0) {
                window.audioChunks.push(e.data);
              }
            };
            
            // 开始录音
            window.mediaRecorder.start();
            console.log("开始录音");
          })
          .catch(function(err) {
            console.error("获取麦克风失败: ", err);
          });
      }
    } catch (e) {
      console.error("录音出错: ", e);
    }
  },
  
  StopRecording: function() {
    try {
      if (window.mediaRecorder && window.mediaRecorder.state === "recording") {
        window.mediaRecorder.stop();
        console.log("正在停止录音...");
        
        window.mediaRecorder.ondataavailable = function(e) {
          console.log("获取到音频数据...");
          var reader = new FileReader();
          reader.onloadend = function() {
            console.log("准备发送数据到Unity...");
            var base64data = reader.result.split(',')[1];
            // 分块发送数据
            var chunkSize = 1024;
            var totalChunks = Math.ceil(base64data.length / chunkSize);
            
            console.log("开始分块发送，总块数：" + totalChunks);
            
            for(var i = 0; i < totalChunks; i++) {
              var chunk = base64data.slice(i * chunkSize, (i + 1) * chunkSize);
              gameInstance.SendMessage('VoiceDialogWebGL', 'ReceiveAudioChunk', 
                JSON.stringify({
                  index: i,
                  total: totalChunks,
                  data: chunk
                })
              );
            }
            console.log("数据发送完成");
          };
          reader.readAsDataURL(e.data);
        };
      }
    } catch (e) {
      console.error("停止录音出错: ", e);
    }
  }
}); 